package com.atguigu.tingshu.order.template;

import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * title:
 * author: zgl
 * date: 2024/3/16
 * description：
 */
@Component
public class OrderTemplate implements ApplicationContextAware {
    private static final ConcurrentHashMap<String, OrderConfirm> MAP = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(OrderKinds.class);
        Collection<Object> values = beans.values();
        values.forEach(bean -> {
            OrderKinds annotation = bean.getClass().getAnnotation(OrderKinds.class);
            MAP.put(annotation.value().type, (OrderConfirm) bean);
        });
    }

    public OrderInfoVo confirm(TradeVo tradeVo) {
        return MAP.get(tradeVo.getItemType()).trade(tradeVo);
    }
}
